import React, {useEffect, useState} from 'react';
import {Modal, Table, Tag} from 'antd';
import type {RoleListItem, updateUserRoleParams, UserListItem} from "../data";
import type {ColumnsType} from "antd/es/table";
import {queryUserRoleList} from "@/pages/system/UserList/service";

interface UpdateUserFormProps {
  open: boolean;
  onCreate: (values: updateUserRoleParams) => void;
  onCancel: () => void;
  item?: UserListItem;
}

const columns: ColumnsType<RoleListItem> = [
  {
    title: '角色名称',
    dataIndex: 'roleName',
    render: (text: string) => <a>{text}</a>,
  },
  {
    title: '排序',
    dataIndex: 'sort',
  },
  {
    title: '状态',
    dataIndex: 'statusId',
    render: (_, {statusId}) => (
      <>
        {
          <Tag color={statusId === 0 ? '#ff4d4f' : '#67c23a'} style={{width: 50, height: 30, textAlign: "center", paddingTop: 4}}>
            {statusId === 0 ? '禁用' : '启用'}
          </Tag>
        }
      </>
    ),
  },
  {
    title: '备注',
    dataIndex: 'remark',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
  },
];

const SetUserRoleForm: React.FC<UpdateUserFormProps> = ({open, onCreate, onCancel, item}) => {
  const [roleList, setRoleList] = useState<RoleListItem[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  useEffect(() => {
    if (open) {
      setRoleList([]);
      setSelectedRowKeys([]);
      queryUserRoleList(item?.id || 0).then((res) => {
        setRoleList(res.data.allRoleList);

        if (res.data.roleIds) {
          setSelectedRowKeys(res.data.roleIds)
        }
      });
    }
  }, [open]);

  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  const handleOk = () => {
    const roleIds = selectedRowKeys.map((i) => Number(i));
    onCreate({userId: item?.id || 0, roleIds})
  }

  const modalFooter = {title: "更新", okText: '保存', onOk: handleOk, onCancel, cancelText: '取消', open, width: 800};

  return (
    <Modal {...modalFooter} style={{top: 150}}>
      <Table rowKey="id" rowSelection={rowSelection} columns={columns} dataSource={roleList}/>
    </Modal>
  );
};

export default SetUserRoleForm;
